package com.waimai.demo.Controller;

import com.sun.deploy.net.HttpResponse;
import com.waimai.demo.back.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class commonController {
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info("滴滴滴" + file);
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName;
        fileName = UUID.randomUUID().toString() + suffix;
        try {
            file.transferTo(new File("D://YUER/" + fileName));
            System.out.println(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("-----------------" + fileName);
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        try {
            FileInputStream inputStream = new FileInputStream(new File("D://YUER/" + name));
            OutputStream outputStream = response.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
